//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Windows.Threading;
using OpenLS.Spreadsheet.AnalysisToolPak;
using OpenLS.Spreadsheet.Extensibility;
using OpenLS.Spreadsheet.Functions;
using OpenLS.Spreadsheet.Serialization;
using DateFunctions=OpenLS.Spreadsheet.StandardAddIn.DateFunctions;

namespace OpenLS.Spreadsheet
{
    public class SpreadsheetContext : IFunctionLocalizer
    {
        private static SpreadsheetContext _default;
        private readonly List<AddIn> _addins = new List<AddIn>();

        public SpreadsheetContext(IEnumerable<AddIn> addins)
        {
            if (addins == null)
                throw new ArgumentNullException("addins");
            _addins.AddRange(addins);
        }

        public IXamlElementResolver XamlElementResolver { get; set; }

        public static SpreadsheetContext Default
        {
            get
            {
                if (_default == null)
                {
                    _default = new SpreadsheetContext(
                        new AddIn[]
                            {
                                new AddIn(typeof (DateFunctions).Assembly),
                                new AddIn(typeof (DateBasisType).Assembly)
                            });
                }
                return _default;
            }
        }

        public IEnumerable<AddIn> AddIns
        {
            get { return _addins; }
        }

        #region IFunctionLocalizer Members

        public string GetLocalName(string name)
        {
            foreach (AddIn addin in AddIns)
            {
                IFunctionLocalizer loc = addin.Localizer;
                if (loc != null)
                {
                    string s = loc.GetLocalName(name);
                    if (s != name)
                        return s;
                }
            }
            return name;
        }

        public string GetGlobalName(string name)
        {
            foreach (AddIn addin in AddIns)
            {
                IFunctionLocalizer loc = addin.Localizer;
                if (loc != null)
                {
                    string s = loc.GetGlobalName(name);
                    if (s != name)
                        return s;
                }
            }
            return name;
        }


        void IFunctionLocalizer.Initialize(IEnumerable<string> globalNames)
        {
        }

        #endregion

        public Function GetFunction(string name, bool localized)
        {
            string upperName = name.ToUpper();
            foreach (AddIn addin in AddIns)
            {
                Function f = addin.GetFunction(upperName, localized);
                if (f != null)
                    return f;
            }
            return null;
        }
    }
}